﻿//-----------------------------------------------------------------------
// <Copyright>
// * Copyright (C) 2022 RuYiAdmin All Rights Reserved
// </Copyright>
//-----------------------------------------------------------------------

using Microsoft.AspNetCore.Http;
using RuYiAdmin.Net.CommonInfrastructure.Configurations;
using RuYiAdmin.Net.CommonInfrastructure.Enums.Business;
using RuYiAdmin.Net.CommonInfrastructure.Utilities.Contexts;
using RuYiAdmin.Net.CommonInfrastructure.Utilities.Utils;
using RuYiAdmin.Net.EntityDataModel.DataTransformationModel.SystemModel;
using System;

namespace RuYiAdmin.Net.EntityDataModel.SessionScope
{
    /// <summary>
    /// Session上下文
    /// </summary>
    public class RuYiSessionContext
    {
        /// <summary>
        /// 当前用户
        /// </summary>
        /// <param name="context">HttpContextAccessor</param>
        /// <returns>用户信息</returns>
        public static SysUserDTO GetCurrentUserInfo(IHttpContextAccessor context)
        {
            var token = context.HttpContext.GetToken();

            var user = RuYiRedisContext.Get<SysUserDTO>(token);

            return user;
        }

        /// <summary>
        /// 当前用户
        /// </summary>
        /// <param name="httpContext">HttpContext</param>
        /// <returns>用户信息</returns>
        public static SysUserDTO GetCurrentUserInfo(HttpContext httpContext)
        {
            var token = httpContext.GetToken();

            var user = RuYiRedisContext.Get<SysUserDTO>(token);

            return user;
        }

        /// <summary>
        /// 获取用户机构编号
        /// </summary>
        /// <param name="context">HttpContextAccessor</param>
        /// <returns>用户机构编号</returns>
        public static Guid GetUserOrgId(IHttpContextAccessor context)
        {
            var orgId = Guid.Empty;

            var user = GetCurrentUserInfo(context);
            if (user.IsSupperAdmin.Equals((int)YesNo.YES) && user.OrgId.Equals(Guid.Empty))
            {
                orgId = RuYiGlobalConfig.SystemConfig.OrgRoot;
            }
            else
            {
                orgId = user.OrgId;
            }

            return orgId;
        }

        /// <summary>
        /// 获取用户机构编号
        /// </summary>
        /// <param name="httpContext">HttpContext</param>
        /// <returns>用户机构编号</returns>
        public static Guid GetUserOrgId(HttpContext httpContext)
        {
            var orgId = Guid.Empty;

            var user = GetCurrentUserInfo(httpContext);
            if (user.IsSupperAdmin.Equals((int)YesNo.YES) && user.OrgId.Equals(Guid.Empty))
            {
                orgId = RuYiGlobalConfig.SystemConfig.OrgRoot;
            }
            else
            {
                orgId = user.OrgId;
            }

            return orgId;
        }
    }
}
